'use strict';
const crypto = require('crypto');
module.exports = app => {

  return class LoginService extends app.Service {
    async post(login) {
      const ctx = this.ctx;
      const cfg = app.config.prefix;
      let password = app.getMD5Value(login.password);
      const loginArg = {
        login_name: +login.user_id,
        password: password,
        org_name: 'nd',
      };
      const tokenResult = await ctx.curl(cfg.API_PREFIX + 'tokens', {
        method: 'POST',
        contentType: 'json',
        data: loginArg,
        dataType: 'json',
      });

      if (tokenResult.data.user_id) {
        // 如果用户第一次登录本站则写入相关信息
        const isExistUser = await this.isExistUser(+tokenResult.data.user_id);
        if (!isExistUser) {
          let userResult = await ctx.curl(cfg.API_PREFIX + 'users/' + tokenResult.data.user_id, {
            contentType: 'json',
            dataType: 'json',
            headers: {
              Authorization: ctx.helper.genAuthHeader(tokenResult.data.access_token, tokenResult.data.mac_key, cfg.API_PREFIX + 'users/' + tokenResult.data.user_id, 'GET'),
            },
          });
          userResult = userResult.data;
          if (userResult.code && userResult.message) {
            return userResult;
          }
          const user_avatar = cfg.AVATAR_PREFIX + tokenResult.data.user_id + '/' + tokenResult.data.user_id + '.jpg';
          // 设置部门小伙伴的默认权限
          let userType = 0;
          if (app.config.adminUser.indexOf(userResult.user_id) > -1) {
            userType = 1;
          }
          // if (userResult.org_exinfo.node_name.indexOf('网站中心') !== -1) {
          //   userType = 2;
          // }
          return await ctx.model.User.create({
              user_name: '未设置',
              password: password,
              user_id: userResult.user_id,
              nick_name: userResult.nick_name,
              real_name: userResult.org_exinfo.real_name,
              email: userResult.email,
              mobile: userResult.mobile,
              avatar: user_avatar,
              gender: userResult.org_exinfo.gender,
              grade_name: userResult.org_exinfo.grade_name,
              grade_value: userResult.org_exinfo.grade_value,
              org_node_name: userResult.org_exinfo.node_name,
              user_type: userType,
              created_ip: ctx.helper.ip2int(ctx.ip),
              create_time: new Date(),
              updated_ip: ctx.helper.ip2int(ctx.ip),
              update_time: new Date(),
            });


        } else {
          // 更新最后登录IP与最后登录时间
          const updateBody = {
            updated_at: ctx.helper.date2unix(),
            updated_ip: ctx.helper.ip2int(ctx.ip),
          };
          const user = await ctx.service.user.update(+tokenResult.data.user_id, updateBody);
          return user;
        }
      } else {
        return tokenResult.data;
      }
    }

    /**
     * 判断当前用户是否存在
     * @param {Number} user_id 用户ID
     * @return {Boolean} 返回是否存在用户
     */
    async isExistUser(user_id) {
      const user = await this.ctx.model.User.findOne({
        where: {
          user_id
        },
        attributes: ['id', 'user_id', 'real_name', 'nick_name', 'avatar', 'user_type'],
      });
      if (!user) {
        return false;
      }
      return true;
    }
  };
};